

use std::{cell::RefCell, rc::Rc};

use serde::{ser::{SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple, SerializeTupleStruct, SerializeTupleVariant}, Serialize};

use crate::{preprocessor::{F32Type, F64Type, Preprocessor, PreprocessorRefData}, types::{serialize_usize, SerNone, XRType}};
pub struct Serializer;

impl Serializer {
    pub fn serialize<T: serde::Serialize + ?Sized>(v:&T)->Result<Vec<u8>, crate::error::Error>{
        let data = v.serialize(Preprocessor::new())?;
        let data = data.borrow().gengrate_refdata();
        let has_ref_block = data.has_ref_data();
        let ref_data = Rc::new(RefCell::new(data));
        let mut head_data:u8 = 0;
        if has_ref_block {
            head_data = 1;
        }
        let mut head:Vec<u8> = vec![0x59, 0x55, 1<<4, head_data];
        if has_ref_block {
            //这里需要新建一个空的PreprocessorRefData，否则引用会继续引用
            let mut array = XRArray::new(Rc::new(RefCell::new(PreprocessorRefData::new(Vec::new()))));
            for data in ref_data.borrow().get_ref_array().iter() {
                match data {
                    crate::preprocessor::PreprocessType::Int(i32) => array.xrserialize_value(i32)?,
                    crate::preprocessor::PreprocessType::F32(F32Type{value, ..}) => array.xrserialize_value(value)?,
                    crate::preprocessor::PreprocessType::F64(F64Type{value, ..}) => array.xrserialize_value(value)?,
                    crate::preprocessor::PreprocessType::String(str) => array.xrserialize_value(str)?,
                }
            }
            head.append(&mut array.xrserialize_end()?);
        }
        let serializer = SerdeSerializer::new(ref_data.clone());
        head.append(&mut v.serialize(serializer)?);
        Ok(head)
    }
}

struct SerdeSerializer {
    preprocess_data: Rc<RefCell<PreprocessorRefData>>,
}

impl SerdeSerializer {
    fn new(preprocess_data: Rc<RefCell<PreprocessorRefData>>) -> Self {
        SerdeSerializer {
            preprocess_data,
        }
    }
}

impl SerdeSerializer {
    fn serialize_ref(&self, index:usize)->Result<Vec<u8>, crate::error::Error> {
        crate::types::RefType(index).serialize()
    }

    fn serialize_u8_ref(&self, v: u8) -> Result<Vec<u8>, crate::error::Error> {
        if let Some(count) = self.preprocess_data.borrow().get_int_refindex(v as i128) {
            self.serialize_ref(*count)            
        }
        else {
            crate::types::XRType::serialize(&v)
        }
    }
}

struct XRArray{
    data:Vec<u8>,
    count:usize,
    ref_data:Rc<RefCell<PreprocessorRefData>>
}

impl XRArray {
    fn new(ref_data:Rc<RefCell<PreprocessorRefData>>)->Self {
        XRArray{
            ref_data,
            data:Vec::new(),
            count: 0
        }
    }

    fn xrserialize_value<T>(&mut self, value: &T) -> Result<(), crate::error::Error>
    where
        T: ?Sized + serde::Serialize {
        self.data.append(&mut value.serialize(SerdeSerializer::new(self.ref_data.clone()))?);
        self.count += 1;
        Ok(())
    }

    fn xrserialize_end(&self) -> Result<Vec<u8>, crate::error::Error> {
        let mut  head_data = serialize_usize(crate::types::Types::Array, self.count)?;
        head_data.extend_from_slice(&self.data);
        Ok(head_data)
    }
}

impl SerializeSeq for XRArray {
    type Ok = Vec<u8>;

    type Error = crate::error::Error;

    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize {
        self.xrserialize_value(value)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        self.xrserialize_end()
    }
}

impl SerializeTuple for XRArray {
    type Ok = Vec<u8>;

    type Error = crate::error::Error;

    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize {
        self.xrserialize_value(value)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        self.xrserialize_end()
    }
}

impl SerializeTupleStruct for XRArray {
    type Ok = Vec<u8>;

    type Error = crate::error::Error;

    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize {
        self.xrserialize_value(value)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        self.xrserialize_end()
    }
}

struct XRObject {
    data:Vec<u8>,
    count:usize,
    ref_data:Rc<RefCell<PreprocessorRefData>>
}

impl XRObject {
    fn new(ref_data:Rc<RefCell<PreprocessorRefData>>)->Self {
        XRObject{
            ref_data,
            data:Vec::new(),
            count: 0
        }
    }

    fn xrserialize_value<T>(&mut self, value: &T) -> Result<(), crate::error::Error>
    where
        T: ?Sized + serde::Serialize {
        self.data.append(&mut value.serialize(SerdeSerializer::new(self.ref_data.clone()))?);
        Ok(())
    }

    fn xrserialize_end(&self) -> Result<Vec<u8>, crate::error::Error> {
        let mut  head_data = serialize_usize(crate::types::Types::Object, self.count)?;
        head_data.extend_from_slice(&self.data);
        Ok(head_data)
    }
}

impl SerializeMap for XRObject {
    type Ok = Vec<u8>;

    type Error = crate::error::Error;

    fn serialize_key<T>(&mut self, key: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize {
        self.xrserialize_value(key)
    }

    fn serialize_value<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize {
        self.xrserialize_value(value)
    }

    fn serialize_entry<K, V>(&mut self, key: &K, value: &V) -> Result<(), Self::Error>
        where
            K: ?Sized + serde::Serialize,
            V: ?Sized + serde::Serialize, {
        self.serialize_key(key)?;
        self.serialize_value(value)?;
        self.count += 1;
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        self.xrserialize_end()
    }
}

impl SerializeStruct for XRObject {
    type Ok = Vec<u8>;

    type Error = crate::error::Error;

    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + serde::Serialize {
        SerializeMap::serialize_entry(self, key, value)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        self.xrserialize_end()
    }
}

// impl SerializeStructVariant for XRObject {
//     type Ok = Vec<u8>;

//     type Error = crate::error::Error;

//     fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
//     where
//         T: ?Sized + serde::Serialize {
//         SerializeMap::serialize_entry(self, key, value)
//     }

//     fn end(self) -> Result<Self::Ok, Self::Error> {
//         self.xrserialize_end()
//     }
// }

struct XRVarientTuple{
    name:String,
    array:XRArray
}

impl XRVarientTuple {
    fn new(name:String, ref_data:Rc<RefCell<PreprocessorRefData>>)->Self{
        XRVarientTuple {
            name,
            array:XRArray::new(ref_data)
        }
    }
}

impl SerializeTupleVariant for XRVarientTuple {
    type Ok = Vec<u8>;

    type Error = crate::error::Error;

    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + Serialize {
        self.array.xrserialize_value(value)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        let mut head = serialize_usize(crate::types::Types::Object, 1)?;
        let mut name_bytes = self.name.as_str().serialize(SerdeSerializer::new(self.array.ref_data.clone()))?;
        let mut end_bytes = self.array.xrserialize_end()?;
        head.append(&mut name_bytes);
        head.append(&mut end_bytes);
        Ok(head)
    }
}

struct XRVarientObject {
    name:String,
    object:XRObject
}

impl XRVarientObject {
    fn new(name:String, ref_data:Rc<RefCell<PreprocessorRefData>>)->Self{
        XRVarientObject {
            name,
            object:XRObject::new(ref_data)
        }
    }
}

impl SerializeStructVariant for XRVarientObject {
    type Ok = Vec<u8>;

    type Error = crate::error::Error;
    
    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + Serialize {
        SerializeMap::serialize_entry(&mut self.object, key, value)
    }
    
    fn end(self) -> Result<Self::Ok, Self::Error> {
        let mut head = serialize_usize(crate::types::Types::Object, 1)?;
        let mut name_bytes = self.name.as_str().serialize(SerdeSerializer::new(self.object.ref_data.clone()))?;
        let mut end_bytes = self.object.xrserialize_end()?;
        head.append(&mut name_bytes);
        head.append(&mut end_bytes);
        Ok(head)
    }
}

impl serde::Serializer for SerdeSerializer {
    type Ok = Vec<u8>;

    type Error = crate::error::Error;

    type SerializeSeq = XRArray;

    type SerializeTuple = XRArray;

    type SerializeTupleStruct = XRArray;

    type SerializeTupleVariant = XRVarientTuple;

    type SerializeMap = XRObject;

    type SerializeStruct = XRObject;

    type SerializeStructVariant = XRVarientObject;

    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
        crate::types::XRType::serialize(&v)
    }

    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
        if let Some(count) = self.preprocess_data.borrow().get_int_refindex(v as i128) {
            self.serialize_ref(*count)            
        }
        else {
            crate::types::XRType::serialize(&v)
        }
    }

    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
        if let Some(count) = self.preprocess_data.borrow().get_int_refindex(v as i128) {
            self.serialize_ref(*count)            
        }
        else {
            crate::types::XRType::serialize(&v)
        }
    }

    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
        if let Some(count) = self.preprocess_data.borrow().get_int_refindex(v as i128) {
            self.serialize_ref(*count)            
        }
        else {
            crate::types::XRType::serialize(&v)
        }
    }

    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
        if let Some(count) = self.preprocess_data.borrow().get_int_refindex(v as i128) {
            self.serialize_ref(*count)            
        }
        else {
            crate::types::XRType::serialize(&v)
        }
    }

    fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
        if let Some(count) = self.preprocess_data.borrow().get_int_refindex(v) {
            self.serialize_ref(*count)            
        }
        else {
            crate::types::XRType::serialize(&v)
        }
    }

    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
        if let Some(count) = self.preprocess_data.borrow().get_int_refindex(v as i128) {
            self.serialize_ref(*count)            
        }
        else {
            crate::types::XRType::serialize(&v)
        }
    }

    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
        if let Some(count) = self.preprocess_data.borrow().get_int_refindex(v as i128) {
            self.serialize_ref(*count)            
        }
        else {
            crate::types::XRType::serialize(&v)
        }
    }

    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
        if let Some(count) = self.preprocess_data.borrow().get_int_refindex(v as i128) {
            self.serialize_ref(*count)            
        }
        else {
            crate::types::XRType::serialize(&v)
        }
    }

    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
        if let Some(count) = self.preprocess_data.borrow().get_int_refindex(v as i128) {
            self.serialize_ref(*count)            
        }
        else {
            crate::types::XRType::serialize(&v)
        }
    }

    fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
        if let Some(count) = self.preprocess_data.borrow().get_int_refindex(v as i128) {
            self.serialize_ref(*count)            
        }
        else {
            crate::types::XRType::serialize(&v)
        }
    }

    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
        if let Some(count) = self.preprocess_data.borrow().get_f32_refindex(v) {
            self.serialize_ref(*count)            
        }
        else {
            crate::types::XRType::serialize(&v)
        }
    }

    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
        if let Some(count) = self.preprocess_data.borrow().get_f64_refindex(v) {
            self.serialize_ref(*count)            
        }
        else {
            crate::types::XRType::serialize(&v)
        }
    }

    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
        let str = v.to_string();
        if let Some(count) = self.preprocess_data.borrow().get_string_refindex(str) {
            self.serialize_ref(*count)
        }
        else {
            crate::types::XRType::serialize(&v.to_string())
        }
    }

    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
        if let Some(count) = self.preprocess_data.borrow().get_string_refindex(v.to_string()) {
            self.serialize_ref(*count)
        }
        else {
            crate::types::XRType::serialize(&v.to_string())
        }
    }

    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
        let mut data:Vec<u8> = vec![];
        for i in v {
            let mut result = self.serialize_u8_ref(*i);
            if let Ok(ref mut result) = result {
                data.append(result);
            } else {
                return result;
            }
        }
        Ok(data)
    }

    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
        SerNone(false).serialize()
    }

    fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + serde::Serialize {
        value.serialize(self)
    }

    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
        SerNone(false).serialize()
    }

    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
        XRArray::new(self.preprocess_data.clone()).xrserialize_end()
    }

    fn serialize_unit_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
    ) -> Result<Self::Ok, Self::Error> {
        serde::Serializer::serialize_str(self, variant)
    }

    fn serialize_newtype_struct<T>(
        self,
        _name: &'static str,
        value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + serde::Serialize {
        value.serialize(self)
    }

    fn serialize_newtype_variant<T>(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + serde::Serialize {
        let mut obj = XRObject::new(self.preprocess_data.clone());
        obj.serialize_entry(variant, value)?;
        obj.xrserialize_end()
    }

    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
        Ok(XRArray::new(self.preprocess_data.clone()))
    }

    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
        Ok(XRArray::new(self.preprocess_data.clone()))
    }

    fn serialize_tuple_struct(
        self,
        _name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
        Ok(XRArray::new(self.preprocess_data.clone()))
    }

    fn serialize_tuple_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
        Ok(XRVarientTuple::new(variant.to_owned(), self.preprocess_data))
    }

    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
        Ok(XRObject::new(self.preprocess_data))
    }

    fn serialize_struct(
        self,
        _name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStruct, Self::Error> {
        Ok(XRObject::new(self.preprocess_data))
    }

    fn serialize_struct_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStructVariant, Self::Error> {
        Ok(XRVarientObject::new(variant.to_owned(), self.preprocess_data))
    }
}



